package org.ssq.mybatisPlusMonitor;

import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.ssq.mybatisPlusMonitor.Interceptor.SlowSqlLogInterceptor;
import org.ssq.mybatisPlusMonitor.services.SlowSqlLogService;

import javax.annotation.Resource;
import java.util.Properties;

@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class, PerformanceInterceptor.class})//只有存在sql且拥有plus才会加载
//@EnableConfigurationProperties(MybatisPlusProperties.class)//读配置文件
@EnableConfigurationProperties(MybatisPlusMonitorProperties.class)//读配置文件
@Configuration
public class MybatisPlusMonitorAutoConfiguration {

    @Value("${mybatis-plus.monitor.max-time}")
    private Long maxtime;
    @Resource
    private SlowSqlLogService slowSqlLogService;


    @Bean
    @ConditionalOnProperty(value = "mybatis-plus-monitor.enabled", havingValue = "true", matchIfMissing = true)
    public SlowSqlLogInterceptor mybatisInterceptor(MybatisPlusMonitorProperties  mybatisPlusMonitorProperties) {
        SlowSqlLogInterceptor sqlLoggerInterceptor = new SlowSqlLogInterceptor();
        slowSqlLogService.CreateSqlLog("slow_sql_log");
        Properties properties = new Properties();
        properties.setProperty("maxtime", String.valueOf(mybatisPlusMonitorProperties.getMaxTime()));
        sqlLoggerInterceptor.setProperties(properties);
        return sqlLoggerInterceptor;
    }
}
